package com.situ.shoplook.common.service.impl;

import com.situ.shoplook.common.service.UploadFileService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * 功能：
 *
 * @author 千堆雪
 * @version 1.0.0
 * <p>
 * created by 千堆雪 on 2024/8/11, last modified by 千堆雪 on 2024/8/11
 */
@Service
public class UploadFileServiceImpl implements UploadFileService {
    //文件上传本地路径
    @Value("${upload.file.path}")
    private String imageUploadPath;
    //文件上传服务器访问地址前缀
    @Value("${upload.server.prefix}")
    private String uploadServerPrefix;

    /**
     * 上传头像，返回图片地址
     *
     * @param file 头像文件
     * @return
     */
    @SuppressWarnings("all")
    @Override
    public String uploadImage(MultipartFile file, String type) {
        String fileName = file.getOriginalFilename();//上传文件名
        int idx = fileName.lastIndexOf(".");
        String ext = fileName.substring(idx);//扩展名
        fileName = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS"));
        fileName += ext;

        File dest = new File(imageUploadPath + "/images/" + type + "/");
        if (!dest.exists()) {
            dest.mkdirs();
        }

        try {
            dest = new File(dest.getCanonicalPath() + "/" + fileName);
            file.transferTo(dest);//传输文件

            return uploadServerPrefix + "images/" + type + "/" + fileName;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
